<template>
  <div class="app-container home">
    <div class="count-info">
      <div class="count-info-item device-count" @click="goToLink">
        <div class="count-info-label">班级数</div>
        <div class="count-info-number">
          <CountTo
            :startVal="0"
            :endVal="indexCount.deviceCount || 123"
            :duration="1500"
          />
        </div>
      </div>
      <div class="count-info-item online-count" @click="goToLink">
        <div class="count-info-label">学生数</div>
        <div class="count-info-number">
          <CountTo
            :startVal="0"
            :endVal="indexCount.onlineCount || 888"
            :duration="1500"
          />
        </div>
      </div>
      <div class="count-info-item alarm-count" @click="goToAlarm">
        <div class="count-info-label">题库数</div>
        <div class="count-info-number">
          <CountTo
            :startVal="0"
            :endVal="indexCount.alarmCount || 376"
            :duration="1500"
          />
        </div>
      </div>
      <div class="count-info-item rtc-count" @click="goToRtc">
        <div class="count-info-label">试卷数</div>
        <div class="count-info-number">
          <CountTo
            :startVal="0"
            :endVal="indexCount.recordCount || 376"
            :duration="1500"
          />
        </div>
      </div>
    </div>
    <div class="map-container" ref="mapContainer" />
  </div>
</template>

<script>
import EventBus from "@/utils/eventBus";
import useCallStore from "@/store/modules/call";
import { markRaw } from "vue";
import { deviceType } from "@/constant/deviceType";
import { key, keyCode } from "@/constant/amap";
import AMapLoader from "@amap/amap-jsapi-loader";
import { getIndexCount } from "@/api/core/rtcDevice";
import { mapState } from "pinia";
import helmetPointImageUrl from "@/assets/images/helmet_point.png";
export default {
  setup() {},
  data() {
    return {
      map: null,
      indexCount: {
        deviceCount: 0,
        onlineCount: 0,
        alarmCount: 0,
        recordCount: 0,
      },
      deviceType,
      helmetMarkerMap: markRaw({}),
      markerLayers: null,
    };
  },
  computed: {
    ...mapState(useCallStore, {
      helmetList(store) {
        const rtcDeviceMap = store.rtcDeviceMap;
        const helmetList = [];
        for (const key in rtcDeviceMap) {
          const deviceList = rtcDeviceMap[key];
          for (const device of deviceList) {
            if (device.deviceType === this.deviceType.Helmet.value) {
              helmetList.push(device);
              break;
            }
          }
        }
        return helmetList;
      },
    }),
  },
  watch: {
    helmetList() {
      this.loadLabelMarker();
    },
  },
  created() {
    // this.getIndexCount();
  },
  mounted() {
    // this.initMap()
  },
  methods: {
    async initMap() {
      if (!window.AMap) {
        window._AMapSecurityConfig = {
          securityJsCode: keyCode,
        };
        try {
          await AMapLoader.load({
            key,
            version: "2.0",
            plugins: [
              "AMap.MouseTool",
              "AMap.ContextMenu",
              "AMap.PolyEditor",
              "AMap.MapType",
              "AMap.Scale",
              "AMap.OverView",
              "AMap.ControlBar",
              "Map3D",
              "AMap.DistrictSearch",
              "AMap.MarkerClusterer",
              "AMap.ToolBar",
              "AMap.Geolocation",
              "AMap.MoveAnimation",
            ],
          });
        } catch (e) {
          this.$modal.msgError("地图加载失败");
        }
      }

      this.map = markRaw(
        new AMap.Map(this.$refs.mapContainer, {
          resizeEnable: true,
          rotateEnable: true,
          pitchEnable: true,
          showLabel: true,
          zoom: 16,
          zooms: [2, 30],
          rotation: 0,
          viewMode: "3D",
          skyColor: "#132237",
        })
      );
      const geoLocation = new AMap.Geolocation({
        enableHighAccuracy: true,
        timeout: 5000,
        maximumAge: 0,
        convert: true,
        showButton: true,
        position: "RB",
        offset: [20, 90],
        showMarker: true,
        showCircle: true,
        panToLocation: true,
        zoomToAccuracy: true,
      });
      this.map.addControl(geoLocation);
      geoLocation.getCurrentPosition(() => {});
      this.map.addControl(new AMap.ToolBar());
      this.map.addControl(new AMap.ControlBar());
      this.map.addControl(new AMap.Scale());
      this.map.addControl(new AMap.MapType({ defaultType: 1 }));

      this.markerLayers = markRaw(
        new AMap.LabelsLayer({
          collision: true,
        })
      );
      this.map.add(this.markerLayers);

      this.loadLabelMarker();
    },
    getIndexCount() {
      getIndexCount().then((res) => {
        this.indexCount = res.data || {};
      });
    },
    loadLabelMarker() {
      if (this.map === null) {
        return;
      }
      const deviceList = this.helmetList;
      for (const device of deviceList) {
        const { userId, nickName, latitude, longitude } = device;

        if (latitude === null || longitude === null) {
          continue;
        }

        const labelMarker = this.helmetMarkerMap[userId];
        if (labelMarker) {
          labelMarker.moveTo([longitude, latitude]);
        } else {
          const marker = new AMap.LabelMarker({
            position: [longitude, latitude],
            icon: {
              image: helmetPointImageUrl,
              // offset: [-12, -12]
            },
            text: {
              content: nickName,
              offset: [0, 40],
              style: {
                backgroundColor: "#eee",
                borderColor: "#333",
                borderWidth: 1,
              },
            },
          });

          this.helmetMarkerMap[userId] = marker;

          this.markerLayers.add(marker);
          this.map.panTo([longitude, latitude]);
        }
      }
    },
    goToLink() {
      this.$router.replace("/helmet/hat");
    },
    goToAlarm() {
      this.$router.replace("/alarm/alarmRecord");
    },
    goToRtc() {
      this.$router.replace("/rtc/room");
    },
  },
};
</script>

<style scoped lang="scss">
.home {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  // background-image: url("../assets/images/home-bg.png");
  // background-size: cover;
  .count-info {
    width: 100%;
    padding: 15px 0;
    display: flex;
    justify-content: space-evenly;
    align-items: center;
    // border: 1px #ccc solid;

    .count-info-item {
      width: 300px;
      height: 100px;
      top: 124px;
      left: 376px;

      .count-info-number {
        font-family: PingFangSC;
        color: #ffffff;
        font-weight: 500;
        font-size: 40px;
        line-height: 26px;
        font-style: normal;
        text-decoration: none;
        text-align: left;
        padding-left: 25px;
        padding-top: 20px;
      }

      .count-info-label {
        font-family: PingFangSC;
        color: #ffffff;
        font-weight: 500;
        font-size: 20px;
        line-height: 26px;
        font-style: normal;
        text-decoration: none;
        text-align: left;
        padding-left: 25px;
        padding-top: 15px;
      }
    }

    .device-count {
      background-image: url("../../src/assets/images/device.png");
      background-repeat: no-repeat;
      background-position-x: 145px;
      background-position-y: 0;
      display: block;
      cursor: pointer;
      border-radius: 20px 20px 20px 20px;
      background-color: #476af7;
      box-shadow: 0 15px 30px 0 rgba(30, 72, 220, 0.2);
    }

    .online-count {
      background-image: url("../../src/assets/images/online.png");
      background-repeat: no-repeat;
      background-position-x: 115px;
      background-position-y: 0;
      display: block;
      cursor: pointer;
      border-radius: 20px 20px 20px 20px;
      background-color: #476af7;
      box-shadow: 0 15px 30px 0 rgba(30, 72, 220, 0.2);
    }

    .alarm-count {
      background-image: url("../../src/assets/images/alarm.png");
      background-repeat: no-repeat;
      background-position-x: -20px;
      background-position-y: -85px;
      display: block;
      cursor: pointer;
      border-radius: 20px 20px 20px 20px;
      background-color: #476af7;
      box-shadow: 0 15px 30px 0 rgba(30, 72, 220, 0.2);
    }

    .rtc-count {
      background-image: url("../../src/assets/images/rtc.png");
      background-repeat: no-repeat;
      background-position-x: 165px;
      background-position-y: 3px;
      display: block;
      cursor: pointer;
      border-radius: 20px 20px 20px 20px;
      background-color: #476af7;
      box-shadow: 0 15px 30px 0 rgba(30, 72, 220, 0.2);
    }
  }

  .map-container {
    width: 100%;
    flex: 1;
  }
}
</style>
